package com.faithbj.common.security;

import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.faithbj.common.dao.UserDao;
import com.faithbj.common.model.Roles;
import com.faithbj.common.model.User;
import com.faithbj.common.utils.FaithbjUtil;
import com.faithbj.common.utils.LogUtil;



/**
 * User: yfxue
 * Date: 12-02-19
 * Time: 上午07:39
 */
@Service("customerUserDetailsService")
@Transactional
public class CustomerUserDetailsService implements UserDetailsService {

    protected static final Logger log = LoggerFactory.getLogger(CustomerUserDetailsService.class);

    @Resource
	private UserDao userDao;
    
    @Resource
    private FaithbjUtil faithbjUtil;
    
    @Resource
    private LogUtil logUtil;
    
	public User loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		User user = userDao.getUserByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("管理员[" + username + "]不存在!");
		}
		
		// 解除管理员账户锁定
		if (user.isAccountNonLocked() == true) {
			
			if (faithbjUtil.getIsLoginFailureLock() == true) 
			{//开启用户锁定功能
				int loginFailureLockTime = faithbjUtil.getLoginFailureLockTime();
				if (loginFailureLockTime != 0) {
					Date lockedDate = user.getLockedDate();
					Date nonLockedTime = DateUtils.addMinutes(lockedDate, loginFailureLockTime);
					Date now = new Date();
					if (now.after(nonLockedTime)) {
						user.setLoginFailureCount(0);
						user.setAccountNonLocked(true);
						user.setLockedDate(null);
						userDao.update(user);
					}
				}
			} 
			else 
			{
				user.setLoginFailureCount(0);
				user.setAccountNonLocked(true);
				user.setLockedDate(null);
				userDao.update(user);
			}
		}
		user.setAuthorities(getGrantedAuthorities(user));
		logUtil.logUserLogInfo(user, "登录");
		return user;
	}
    
	// 获得管理角色数组
	public Collection<SimpleGrantedAuthority> getGrantedAuthorities(User member) {
		Set<SimpleGrantedAuthority> grantedAuthorities = new HashSet<SimpleGrantedAuthority>();
		for (Roles role : member.getRoles()) {
			grantedAuthorities.add(new SimpleGrantedAuthority(role.getValue()));
		}
		return grantedAuthorities;
	}
}
